﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Speech.Synthesis;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Speech.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        private static string OldMessage = string.Empty;

        public async Task GetSpeek(string context)
        {
            try
            {
                if (!string.IsNullOrEmpty(OldMessage))
                {
                    if (OldMessage == context)//重复信息不处理
                        return;
                }

                OldMessage = context;

                using (SpeechSynthesizer hello = new SpeechSynthesizer())
                {
                    var speek = hello.SpeakAsync(context);
                    while (!speek.IsCompleted)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    Debug.WriteLine(context);
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        hello.SetOutputToWaveStream(ms);

                        HttpContext.Response.ClearContent();
                        HttpContext.Response.ContentType = "audio/mp3";
                        HttpContext.Response.BinaryWrite(ms.ToArray());
                        //Dispose
                        await ms.FlushAsync();
                        ms.Close();

                        hello.Dispose();//将占用的语音资源释放，否则后续会出现异步资源被占用情况
                        HttpContext.Response.Close();
                        //HttpContext.Request.Abort();
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}